import { getToken } from "@/utils/cache";
import {Config} from "@/common/config";

const headers = () => {
	let headers = {
		'content-type': 'application/json',
		Authorization: ''
	};
	const token = getToken()
	if (token) {
		headers.Authorization = `Bearer ${token}`
	}
	return headers
}

// @ts-ignore
export const request = <T>(params : UniApp.RequestOptions): Promise<T> => {
	return new Promise((resolve, reject) => {
		// @ts-ignore
		uni.request({
			//url: `${Config.baseUrl}${params.url}`,
			...params,
			method: params.method || 'POST',
			timeout: params.timeout || 100000,
			header: headers(),
			success: (res) => {
				console.log('接口响应:', res);
				resolve(res)
			},
			fail: (err: any) => {
				console.log('错误信息:', err);
				reject(err)
			}
		});

	})
}

// @ts-ignore
export const upload= <T>(params : UniApp.RequestOptions, token: string): Promise<T> => {
	return new Promise((resolve, reject) => {
		// @ts-ignore
		uni.showLoading({
			title: "上传中",
		});

		console.log(`${Config.BASE_API}${params.url}`)
		// @ts-ignore
		let header = headers()
		// @ts-ignore
		header.token = token
		// @ts-ignore
		uni.uploadFile({
			url: `${Config.BASE_API}${params.url}`,
			filePath: params.data.file,
			name: 'file',
			header: header,
			formData: {},
			success: (uploadFileRes:any) => {
				// @ts-ignore
				uni.hideLoading();
				if (uploadFileRes.data && uploadFileRes.statusCode === 200) {
					resolve(uploadFileRes.data)
				} else {
					reject(uploadFileRes)
				}
			},
			fail: (err:any) => {
				console.error(err)
				// @ts-ignore
				uni.hideLoading();
				reject(err)
			}
		});
	})
}
